package com.game.view
{
	import config.Config;
	
	import flash.display.Bitmap;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.Event;
	
	public class ViewerBase extends MovieClip
	{
		public function ViewerBase()
		{
			super();
			stop();
			beforeAdded();
			addEventListener(Event.ADDED_TO_STAGE, __onAdded,false,0,true);
			addEventListener(Event.REMOVED_FROM_STAGE, __onRemoved,false,0,true);
		}
		
		public var needDestroyWhenRemove:Boolean = true;
		public var content:Sprite;
		protected var isFirstAdded:Boolean = false;
		protected var isFirstRemoved:Boolean = false;
		
		protected function get gc():Config
		{
			return Config.getIns();
		}
		
		/**
		 * 添加到舞台前调用，可用于初始化资源
		 * 在子类调用super()时就会调用
		 */
		protected function beforeAdded():void
		{
		}
		
		/**
		 * 每一次添加到舞台后调用
		 */
		protected function onAdded():void
		{
		}
		
		/**
		 * 第一次添加到舞台后调用
		 */
		protected function onFirstAdded():void
		{
		}
		
		/**
		 * 每一次从舞台移除前调用，调用后就会从舞台移除
		 */
		protected function beforeRemoved():void
		{
		}
		
		/**
		 * 每一次从舞台移除后调用
		 */
		protected function onRemoved():void
		{
		}
		
		/**
		 * 第一次从舞台移除后调用，优先级比onRemoved高
		 */
		protected function onFirstRemoved():void
		{
		}
		
		public function removeFromParent(... rest):void
		{
			beforeRemoved();
			if(parent && parent.contains(this))
			{
				parent.removeChild(this);
			}
		}
		
		public function removeAllChildren():void
		{
			graphics.clear();
			while (numChildren)
			{
				var obj:DisplayObject = getChildAt(0);
				if (obj is Bitmap)
				{
					Bitmap(obj).bitmapData.dispose();
					Bitmap(obj).bitmapData = null;
				}
				removeChildAt(0);
			}
		}
		
		private function __onAdded(param1:Event):void
		{
			removeEventListener(Event.ADDED_TO_STAGE, __onAdded);
			if(!isFirstAdded)
			{
				isFirstAdded = true;
				onFirstAdded();
			}
			onAdded();
		}
		
		private function __onRemoved(param1:Event):void
		{
			removeEventListener(Event.REMOVED_FROM_STAGE, __onRemoved);
			if(!isFirstRemoved)
			{
				isFirstRemoved = true;
				onFirstRemoved();
			}
			onRemoved();
			if(!needDestroyWhenRemove)
			{
				return;
			}
			while (numChildren)
			{
				var _loc1_:DisplayObject = removeChildAt(0);
				if(_loc1_ is Bitmap && Bitmap(_loc1_).bitmapData)
				{
					Bitmap(_loc1_).bitmapData.dispose();
				}
			}
		}
	}
}
